<template>
    <div v-if="visible">
        <el-drawer :title="title" :append-to-body="true" :before-close="handleClose" :size="500" :visible.sync="visible"
            :modal="false" v-if="visible" direction="rtl" custom-class="drawer" :destroyOnClose="true" ref="drawer">
            <div class="drawer__content" v-loading="loading">
                <el-form :model="form" :rules="rules" ref="form">
                    <el-form-item prop="headimg_url" label="学员头像" :label-width="formLabelWidth">
                        <div class="uploadcol">
                            <div class="uploadborder">
                                <img v-if="form.headimg_url" :src="form.headimg_url" />
                                <img v-else src="@/assets/img/uploadimg.jpg" />
                            </div>
                            <el-button type="primary" @click="isShowPic = true" size="mini"
                                style="margin-top:10px">上传头像</el-button>

                        </div>
                        <select-img :show="isShowPic" @update="cleanDiaglog" :selectType="imgnum" :source="1"
                            @selectSure="selectImgs" :type="0"></select-img>
                    </el-form-item>
                    <el-form-item prop="account" label="学员账号" :label-width="formLabelWidth">
                        <el-input v-model="form.account" size="mini" maxlength="50" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item prop="nickname" label="学员昵称" :label-width="formLabelWidth">
                        <el-input v-model="form.nickname" size="mini" maxlength="50" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item prop="sy_order_num" label="私域订单号" :label-width="formLabelWidth" class="sy_order_num">
                        <template v-if="id">
                            <el-input v-model="form.sy_order_num" disabled size="mini" maxlength="250"
                                placeholder="请输入"></el-input>
                        </template>
                        <template v-else>
                            <div>
                                <el-input v-model="form.sy_order_num" size="mini" maxlength="250"
                                    placeholder="请输入"></el-input>
                                <el-button @click.stop="checkOrder" size="mini" type="primary">校验</el-button>
                            </div>
                        </template>

                    </el-form-item>
                    <el-form-item prop="mobile" label="手机号" :label-width="formLabelWidth">
                        <el-input v-model="form.mobile" size="mini" maxlength="11" placeholder="请输入手机号"></el-input>
                    </el-form-item>
                    <el-form-item prop="nickname_remark" label="学员备注" :label-width="formLabelWidth">
                        <el-input v-model="form.nickname_remark" size="mini" maxlength="50"
                            placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item prop="gender" label="学员性别" :label-width="formLabelWidth">
                        <el-radio-group v-model="form.gender">
                            <el-radio :label="1">男</el-radio>
                            <el-radio :label="2">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item prop="birthday" label="学员生日" :label-width="formLabelWidth">
                        <el-date-picker value-format="yyyy-MM-dd" v-model="form.birthday" type="date" size="mini"
                            :picker-options="{
                                disabledDate(time) {
                                    return time.getTime() > new Date().getTime();
                                }
                            }" placeholder="选择日期">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item prop="school" label="就读学校" :label-width="formLabelWidth">
                        <el-input v-model="form.school" size="mini" maxlength="255" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item prop="grade" label="学员年级" :label-width="formLabelWidth" size="mini">
                        <el-select v-model="form.grade" placeholder="请选择">
                            <el-option v-for="item in gradeList" :label="item.grade_name" :key="item.id"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="end_date_type" label="截止日期" :label-width="formLabelWidth">
                        <el-radio-group v-if="!form.id" v-model="form.end_date_type">
                            <el-radio :label="1">一年</el-radio>
                            <el-radio :label="2">自定义</el-radio>
                        </el-radio-group>
                        <div v-if="form.end_date_type == 2 || form.id">
                            <el-date-picker v-model="form.end_date" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
                                size="mini" placeholder="选择日期">
                            </el-date-picker>
                        </div>

                    </el-form-item>
                    <el-form-item prop="address" label="家庭住址" :label-width="formLabelWidth">
                        <el-cascader size="small" :options="regionData" v-model="form.city_code" @change="handleChange"
                            placeholder="请选择省市区" style='width:100%'></el-cascader>
                        <el-input v-if="form.city_code.length" v-model="form.address" size="mini" maxlength="255"
                            type="textarea" autosize placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item prop="remark" label="备注" :label-width="formLabelWidth">
                        <el-input v-model="form.remark" size="mini" maxlength="100" type="textarea" :rows="2"
                            placeholder="请输入详细地址"></el-input>
                    </el-form-item>
                </el-form>
                <div class="drawer__footer">
                    <el-button @click="cancelForm" size="mini">取 消</el-button>
                    <el-button type="primary" size="mini" @click="handleSubmit">确 定</el-button>
                </div>
            </div>

        </el-drawer>
    </div>
</template>
<script>
import { regionData, codeToText } from 'element-china-area-data'
import { addStudent, getStudentDetail, updateStudent, getGradeList, checkUserOrder } from '@/api/kanke/student.js'
import dayjs from 'dayjs';
import { time } from 'echarts';

export default {
    name: 'KanKeStudentAddForm',
    props: {
        visible: {
            type: Boolean,
        },
        id: {
            type: Number,
            default: 0
        },
        handleReload: {
            type: Function
        }
    },
    components: {
    },

    data() {
        return {
            loading: false,
            form: {
                headimg_url: '',
                mobile: '',
                sy_order_num: '',
                nickname: '',
                nickname_remark: '',
                account: '',
                gender: 1,
                birthday: null,
                school: '',
                grade: '',
                end_date_type: '',
                end_date: null,
                address: '',
                remark: '',
                city_name: [],
                city_code: [],
            },
            rules: {
                account: [{
                    required: true,
                    message: '请输入学员账号',
                    trigger: 'blur'
                }, {
                    // 数字字母 6到12位
                    pattern: /^[a-zA-Z0-9]{6,12}$/,
                    message: '请输入6到12位的数字或字母',
                    trigger: 'blur'
                }],
                nickname: [{
                    required: true,
                    message: '请输入学员昵称',
                    trigger: 'blur'
                }],
                sy_order_num: [{
                    required: true,
                    message: '请输入私域订单号',
                    trigger: 'blur'
                }],
                // 验证手机号
                mobile: [{
                    pattern: /^1[3456789]\d{9}$/,
                    message: '请输入正确的手机号',
                    trigger: 'blur'
                }],

            },
            formLabelWidth: '100px',
            dialog: true,
            isShowPic: false,
            imgnum: 1, //选择图片数量,
            regionData,
            cityName: [],
            gradeList: [],
            hasCheckUserOrder: false
        }
    },
    mounted() {
        getGradeList().then(res => {
            if (res.code == 200) {
                this.gradeList = res.data
            }
        })
    },
    computed: {
        title() {
            return !this.id ? '新增学员' : '编辑学员'
        },

    },
    watch: {
        id: {
            handler(newVal) {
                if (newVal) {
                    this.init()
                }
            },
            immediate: true
        },
        'form.sy_order_num': {
            handler(newVal, oldVal) {
                if (newVal && newVal !== oldVal)
                    this.hasCheckUserOrder = false
            }
        }
    },
    methods: {
        init() {
            if (this.id) {
                this.loading = true
                getStudentDetail({ user_id: this.id }).then(res => {
                    this.loading = false
                    if (res.code == 200) {

                        let city_code = res.data.city_code ? JSON.parse(res.data.city_code) : [];
                        let grade = res.data.grade === 0 ? '' : res.data.grade
                        this.form = { ...res.data, city_code, grade }
                    } else {
                        this.$message.error('获取数据失败')
                    }
                })
            }
        },
        checkOrder() {
            const sy_order_num = this.form.sy_order_num
            if (!sy_order_num) {
                this.$message.error('请输入私域订单号')
                return false
            }
            checkUserOrder({ sy_order_num }).then(res => {
                if (res.code == 200) {
                    this.hasCheckUserOrder = true
                    this.$message.success('订单号可用')
                } else {
                    this.$message.error(res.message)
                }
            })
        },

        handleChange(value) {
            this.form.city_code = [...value];
            this.getCode2Text(value)
        },
        getCode2Text(val) {
            let cityName = "";
            switch (val.length) {
                case 1:
                    cityName += codeToText[val[0]];
                    break;
                case 2:
                    cityName += codeToText[val[0]] + "/" + codeToText[val[1]];
                    break;
                case 3:
                    cityName +=
                        codeToText[val[0]] +
                        "/" +
                        codeToText[val[1]] +
                        "/" +
                        codeToText[val[2]];
                    break;
                default:
                    break;
            }
            this.form.city_name = cityName;
        },
        handleClose() {
            this.$refs['form'].resetFields();
            this.$emit('update:visible', false);
        },
        cancelForm() {
            this.$refs['form'].resetFields();
            this.$emit('update:visible', false);
        },
        cleanDiaglog() {
            this.isShowPic = false;
        },
        selectImgs(res) {
            this.form.headimg_url = res[0].urls
            this.isShowPic = false;
        },
        handleSubmit() {
            if (!this.hasCheckUserOrder && !this.form.id) {
                this.$message.error('请先验证订单号')
                return
            }
            this.$refs['form'].validate((valid) => {
                if (!valid) return false
                const params = { ...this.form }

                delete params.end_date_type
                if (this.form.id) {
                    delete params.class_name
                }

                if (this.form.end_date_type == 1 && !this.form.id) {
                    params.end_date = dayjs().add(1, 'year').format('YYYY-MM-DD HH:mm:ss')
                }
                params.city_code = JSON.stringify(this.form.city_code)
                const api = this.form.id ? updateStudent : addStudent
                api(params).then(res => {
                    if (res.code == 200) {
                        this.$emit('update:visible', false);
                        this.$refs['form'].resetFields();
                        this.$message.success(res.msg)
                        this.$emit('handleReload')
                    }
                })
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.drawer {
    &__content {
        margin-bottom: 30px;
    }

    &__footer {
        margin-left: 50px;
    }
}

.uploadcol {
    display: flex;
    align-items: center;
    justify-content: space-around;

    .uploadborder {
        img {
            width: 80px;
            height: 80px;
        }

    }
}


.sy_order_num {

    ::v-deep .el-color-picker__icon,
    .el-input,
    .el-textarea {
        width: 75%;
    }

    ::v-deep .el-button {
        margin-left: 10px;
    }
}
</style>